import {getWxUserProfile} from '../../utils/wx.api'
import {IAppOption} from '../../app.option'
import {routing} from '../../constant/routing.constant'
import {MainItem, MainItemQueryResult, NavItem} from './interfaces'
import {TripService} from '../../service/trip'
import {rental} from '../../service/proto_gen/rental/rental_pb'

const app = getApp<IAppOption>()


Page({
    scrollStates: {
        mainItems: [] as MainItemQueryResult[],
    },
    layoutResolver: undefined as (() => void) | undefined,
    data: {
        promotionItems: [
            {
                img: 'https://img.mukewang.com/5f7301d80001fdee18720764.jpg',
                promotionID: 1,
            },
            {
                img: 'https://img.mukewang.com/5f6805710001326c18720764.jpg',
                promotionID: 2,
            },
            {
                img: 'https://img.mukewang.com/5f6173b400013d4718720764.jpg',
                promotionID: 3,
            },
            {
                img: 'https://img.mukewang.com/5f7141ad0001b36418720764.jpg',
                promotionID: 4,
            },
        ],
        avatarURL: '',
        licStatus: '未认证',
        tripsHeight: 0,
        navCount: 0,
        mainScroll: '',
        navSel: '',
        navScroll: '',
        navItems: [] as NavItem[],
        mainItems: [] as MainItem[],
    },
    /**
     * 渲染完成时
     */
    onReady() {

        // 动态高度
        wx.createSelectorQuery()
            .select('#heading')
            .boundingClientRect(rect => {

                const height = wx.getSystemInfoSync().windowHeight - rect.height

                this.setData({
                    tripsHeight: height,
                    navCount: Math.round(height / 50),
                }, () => {
                    if (this.layoutResolver) {
                        this.layoutResolver()
                    }
                })

            }).exec()

    },
    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad() {

        // const layoutReady = new Promise((resolve) => {
        //     this.layoutResolver = resolve
        // })

        // TODO
        let tripsResponse = await TripService.GetTrips(rental.v1.TripStatus.IN_PROGRESS)
        console.log(tripsResponse)


        // 填充元素
        this.populateItems()

        app.globalData.userInfo.then(res => {
            this.setData({
                avatarURL: res.avatarUrl
            })
        })
    },
    /**
     * 点击获取用户信息
     */
    async onGetUserInfo() {

        const userProfileResp = await getWxUserProfile()

        let userInfo = userProfileResp.userInfo

        if (userInfo) {
            app.resolveUserInfo(userInfo)
            this.setData({
                avatarURL: userInfo.avatarUrl
            })
        }

    },
    /**
     * 促销商品点击
     */
    onPromotionItemTap(e: any) {

        const promotionID: number = e.currentTarget.dataset.promotionId
        if (promotionID) {
            console.log('促销商品ID', promotionID)
        }
    },
    /**
     * 驾照注册
     */
    async onRegisterTap() {

        if (this.data.avatarURL) {
            await wx.navigateTo({
                url: routing.register()
            })
        } else {
            await wx.showToast({
                icon: 'none',
                title: '请先点击头像授权',
            })
        }

    },
    /**
     * 右侧Nav点击
     */
    onNavItemTap(e: any) {

        const mainId: string = e.currentTarget?.dataset?.mainId
        const navId: string = e.currentTarget?.id

        if (mainId && navId) {
            this.setData({
                mainScroll: mainId,
                navSel: navId,
            })
        }

    },
    /**
     * 填充数组
     */
    populateItems() {

        const mainItems: MainItem[] = []
        const navItems: NavItem[] = []
        let prevNavId = ''
        let navSel = ''

        for (let i = 0; i < 30; i++) {

            const mainId = `main-${i}`
            const navId = `nav-${i}`
            const tripId = `${10001 + i}`.toString()
            const shortId = tripId

            // 之前没有元素
            if (!prevNavId) {
                prevNavId = navId
            }

            mainItems.push({
                id: mainId,
                navId: navId,
                navScrollId: prevNavId,
                data: {
                    id: (10001 + i).toString(),
                    shortId,
                    start: '东方明珠',
                    end: '迪士尼',
                    distance: '27.0公里',
                    duration: '0时44分',
                    fee: '128' + i + '.00元',
                    status: '已完成'
                }
            })

            if (i === 0) {
                navSel = navId
            }

            prevNavId = navId

            navItems.push({
                id: navId,
                mainId: mainId,
                label: tripId,
            })


        }
        this.setData({
            mainItems,
            navItems,
            navSel
        }, () => {
            // 控制右侧行程导航滚动左侧也滚动
            this.prepareScrollStates()
        })
    },
    /**
     * 控制右侧行程导航滚动左侧也滚动
     */
    prepareScrollStates() {

        wx.createSelectorQuery().selectAll('.main-item')
            .fields({
                id: true,
                dataset: true,
                rect: true,
            }).exec(res => {
            this.scrollStates.mainItems = res[0]
        })

    },
    onMainScroll(e: any) {

        const top: number = e.currentTarget?.offsetTop + e.detail?.scrollTop

        if (top === undefined) {
            return
        }

        const selItem = this.scrollStates.mainItems.find(v => v.top >= top)

        if (!selItem) {
            return
        }

        this.setData({
            navSel: selItem.dataset.navId,
            navScroll: selItem.dataset.navScrollId,
        })

    },
})
